package com.xuan.yubi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class DLXDirectConsumer {

    private static final String EXCHANGE_NAME = "another-topic-exchange";
    private static final String DLX_EXCHANGE_NAME = "dlx-topic-exchange";
    private static final String DLX_QUEUE_BOSS = "boss";
    private static final String DLX_QUEUE_EMPLOYEE = "employee";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        Connection connection = connectionFactory.newConnection();
        Channel[] channels = new Channel[2];
        String[] queueNames = new String[2];
        Scanner in = new Scanner(System.in);


        for (int i = 0; i < 2; i++) {
            channels[i] = connection.createChannel();
            // 声明交换机名称和类型
            channels[i].exchangeDeclare(EXCHANGE_NAME, "topic");
            // 声明消息队列，持久化保存，当消息没被订阅时队列也不会被删除
            // 并绑定一个死信交换机
            Map<String,Object> args = new HashMap<>();
            args.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
            queueNames[i] = channels[i].queueDeclare("DLXTopicQ" + (i + 1), true, false, false, args).getQueue();
            System.out.println("输入当前消息队列要绑定的路由键:");
            while (in.hasNext()) {
                String routingKey = in.next();
                if ("99999".equals(routingKey)) break;
                channels[i].queueBind(queueNames[i], EXCHANGE_NAME, routingKey);
            }
        }

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        // 接收到消息时的处理逻辑
        DeliverCallback deliverCallback1 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
            try {
                Thread.sleep(40000);
                channels[0].basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        DeliverCallback deliverCallback2 = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
            try {
                Thread.sleep(40000);
                channels[1].basicReject(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        // 开始监听消息
        channels[0].basicConsume(queueNames[0], false, deliverCallback1, consumerTag -> {});
        channels[1].basicConsume(queueNames[1], false, deliverCallback2, consumerTag -> {});
        System.out.println("开始监听消息");

        // 此方法是绑定了死信交换机的死信队列接收消息的处理过程
        receiveDeadLetterMessage(connection);
    }

    private static void receiveDeadLetterMessage(Connection connection) throws IOException {
        Channel channel1 = connection.createChannel();
        Channel channel2 = connection.createChannel();

        channel1.exchangeDeclare(DLX_EXCHANGE_NAME, "topic");
        channel2.exchangeDeclare(DLX_EXCHANGE_NAME, "topic");

        channel1.queueDeclare(DLX_QUEUE_BOSS, true, false, false, null);
        channel2.queueDeclare(DLX_QUEUE_EMPLOYEE, true, false, false, null);

        channel1.queueBind(DLX_QUEUE_BOSS, DLX_EXCHANGE_NAME, "*.orange.*");
        channel2.queueBind(DLX_QUEUE_EMPLOYEE, DLX_EXCHANGE_NAME, "*.*.rabbit");
        channel2.queueBind(DLX_QUEUE_EMPLOYEE, DLX_EXCHANGE_NAME, "lazy.#");

        // 接收到消息时的处理逻辑
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [√] Received DlxMessage'" + message + "'");
        };

        channel1.basicConsume(DLX_QUEUE_BOSS, true, deliverCallback, consumerTag -> {});
        channel2.basicConsume(DLX_QUEUE_EMPLOYEE, true, deliverCallback, consumerTag -> {});
        System.out.println("死信队列开始监听消息");
    }

}